package servlet;

import redis.SecKillRedis;
import redis.SecKillRedisByLua;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

/**
 * 秒杀Servlet
 */
public class SecKillServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        //获取票号
        String tickNo = req.getParameter("ticketNo");
        //生成用户
        String randomUserId = new Random().nextInt(10000) + 1 + "";
        //调用秒杀方法
//        boolean isSuccess = SecKillRedis.secKill(randomUserId, tickNo);
        //调用lua脚本完成秒杀
        boolean isSuccess = SecKillRedisByLua.doSecKill(randomUserId, tickNo);
        //将结果返回给前端
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.print(isSuccess);
        writer.flush();
        writer.close();
    }
}
